package com.bbx.taxi.client.Activity.login;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.autoupdatesdk.BDAutoUpdateSDK;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.SDK;
import com.bbx.api.sdk.model.comm.returns.Svconfigs;
import com.bbx.api.sdk.model.passanger.Return.Jmsg.Msgs.Data;
import com.bbx.api.sdk.model.passanger.Return.Version;
import com.bbx.api.util.LogUtils;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.Activity.Guide.GuideActivity;
import com.bbx.taxi.client.Activity.Main.MainActivity;
import com.bbx.taxi.client.Bean.City;
import com.bbx.taxi.client.Bean.Extra.BasefragmentMsg;
import com.bbx.taxi.client.Bean.Extra.GuideMsg;
import com.bbx.taxi.client.Bean.Message.ObserverListener;
import com.bbx.taxi.client.Bean.Message.Publisher;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.DB.LineDB;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.MyApplication.OnLocationResultListener;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Service.LoginService;
import com.bbx.taxi.client.UpdateChecker.UpdateCheck;
import com.bbx.taxi.client.UpdateChecker.UpdateCheck.OnUpdateListener;
import com.bbx.taxi.client.UpdateChecker.baidu.MyCPCheckUpdateCallback;
import com.bbx.taxi.client.UpdateChecker.baidu.MyCPCheckUpdateCallback.OnBaiduUpdateListener;
import com.bbx.taxi.client.UpdateChecker.qihoo.MyQihooUpdate;
import com.bbx.taxi.client.UpdateChecker.qihoo.MyQihooUpdate.OnQihooUpdateListener;
import com.bbx.taxi.client.UpdateChecker.ui.MyUpdateLoad;
import com.bbx.taxi.client.UpdateChecker.ui.MyUpdateLoad.UpdateType;
import com.bbx.taxi.client.Util.ChannelName;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.Util.IsDataFail;
import com.bbx.taxi.client.Util.NetworkDetector;
import com.bbx.taxi.client.Util.RequestUtils;
import com.bbx.taxi.client.Util.VersionInfo;
import com.bbx.taxi.client.Util.VersionUtils;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickLeftListener;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickRightListener;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickSingleListener;
import com.bbx.taxi.client.widget.StatusBar.StatusBar;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class WelcomeActivity extends FragmentActivity implements OnLocationResultListener,OnUpdateListener,OnBaiduUpdateListener,OnQihooUpdateListener,ObserverListener{
	// 延迟3秒
	private static  long SPLASH_DELAY_MILLIS = 3000;
	/**判断是否开始启动了*/
	private boolean isStart=false;
	private final int GO_MAIN = 1000;
	private final int GO_GUIDE = 1001;
	private final int GO_LOGIN = 1002;
	private long starttime;
	private boolean isFirstIn = false;
//	private TokenTask mTokenTask;
	private LineDB db_line;// 线路数据库
	public static int platform;//0是帮邦行，2001是天山行，1001是公务车,泉州公务车3001
	List<City> cityList=new ArrayList<City>();
	UpdateCheck mUpdateCheck;
	 MyAlertDailog dialog;
    private MyApplication mApplication;
    private Activity context;
	@Bind(R.id.iv_splash)
	ImageView iv_splash;
	private boolean isLocation=true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		  //设置无标题  
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        //设置全屏  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
                WindowManager.LayoutParams.FLAG_FULLSCREEN); 
		setContentView(R.layout.activity_welcome);
		super.onCreate(savedInstanceState);
		ButterKnife.bind(this);
		StatusBar.setTranslucentStatus(this, true);
		mApplication=MyApplication.getInstance();
		mApplication.onStartLocation();
		mApplication.addActivity(this);
		context=this;
		new Handler().postDelayed(new Runnable() {
			
			@Override
			public void run() {
				onStartFragemnt(new WelcomeFragment(),0,0);
			}
		}, 500);
		
		initView();
	}
    @Override
    protected void onResume() {
    	Publisher.getInstance().addOb(this);
    	// app 从后台唤醒，进入前台,不执行。
    	Value.isActive=true;
		RequestUtils.requestLinePlus(context, false);
    	super.onResume();
    }
	protected void initView() {
		switch(VersionUtils.getVersionType(this)){
		case bbx:
			platform=0;
			break;
		case tianshang:
			platform=2001;
			break;
		}
		mApplication.setOnLocationResultListener(this);
		MobclickAgent.updateOnlineConfig(this);
		dialog=new MyAlertDailog(this);
		db_line=new LineDB();
		starttime = DateFormat.getTime();
		mApplication.isFirstClient=true;
		mApplication.isFirstClient2=true;
		SDK.VER=platform+"_"+ChannelName.getAppMetaData(this)+"_"+VersionInfo.getVersion(this);
		if(NetworkDetector.detect(this)){
			switch(Value.isMode){
			case Value.isNormal:
				mUpdateCheck=UpdateCheck.getInstance(this);
				mUpdateCheck.setOnUpdateListener(this,platform,ChannelName.getAppMetaData(this));	
				break;
			case Value.isBaidu:
				//百度SDK
				MyCPCheckUpdateCallback mMyCPCheckUpdateCallback = new MyCPCheckUpdateCallback(context,null,UpdateType.TYPE_QIDONG);
				mMyCPCheckUpdateCallback.setOnBaiduUpdateListener(this);
				BDAutoUpdateSDK.cpUpdateCheck(this, mMyCPCheckUpdateCallback);
				break;
			case Value.is360:
				MyQihooUpdate mMyQihooUpdate = new MyQihooUpdate(context,null,UpdateType.TYPE_QIDONG);
				mMyQihooUpdate.setOnQihooUpdateListener(this);
				mMyQihooUpdate.onStart();
				break;
			}	
		}
		else{
			Toast.makeText(this,getResources().getString(R.string.no_network), Toast.LENGTH_SHORT).show();
			startActivity(2);
		}

	}

	/**
	 * 从Assets中读取图片
	 */
	private Bitmap getImageFromAssetsFile(String fileName) {
		Bitmap image = null;
		AssetManager am = getResources().getAssets();
		try {
			InputStream is = am.open(fileName);
			image = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return image;

	}
	/**
	 * 获取配置
	 */
	private void getOnSvconfig() {
		RequestUtils.requesSvconfig(context);
	}
	/** 跳转类型0为引导页，1为登陆，2为主界面 */
	public void startActivity(int type) {
		isFirstIn = SharedPreUtil.getBooleanValue(this,
				SharedPreEncryptUtil.isFirstIn, true);
		if (isFirstIn) {
			type = 0;
		}
		long currentTime = DateFormat.getTime();
		long differTime = currentTime - starttime;
		if (differTime < SPLASH_DELAY_MILLIS) {
			switch (type) {
			case 0:
				mHandler.sendEmptyMessageDelayed(GO_GUIDE, SPLASH_DELAY_MILLIS
						- differTime);
				break;
			case 1:
				mHandler.sendEmptyMessageDelayed(GO_LOGIN, SPLASH_DELAY_MILLIS
						- differTime);
				break;
			case 2:
				mHandler.sendEmptyMessageDelayed(GO_MAIN, SPLASH_DELAY_MILLIS
						- differTime);
				break;
			}

		} else {
			// 时间已经超过3秒了，直接启动不等待
			switch (type) {
			case 0:
				mHandler.sendEmptyMessage(GO_GUIDE);
				break;
			case 1:
				mHandler.sendEmptyMessage(GO_MAIN);
				break;
			case 2:
				mHandler.sendEmptyMessage(GO_MAIN);
				break;
			}
		}
	}

	/**
	 * Handler:跳转到不同界面
	 */
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (isFinishing()) {
				return;
			}
			Publisher.getInstance().removeOb(WelcomeActivity.this);
			isStart=true;
			switch (msg.what) {
			case GO_GUIDE:
				startActivity(new Intent(WelcomeActivity.this,
						GuideActivity.class).putExtra(GuideMsg.extra_guide,
						GuideMsg.guide_welcome));
				break;
			case GO_LOGIN:
				startActivity(new Intent(WelcomeActivity.this,
						MainActivity.class));
				break;
			case GO_MAIN:
				startActivity(new Intent(WelcomeActivity.this,
						MainActivity.class));
				break;
			}
			super.handleMessage(msg);
		}
	};

	protected void onDestroy() {
		mApplication.removeOnLocationResultListener(this);
		Publisher.getInstance().removeOb(this);
		if(mUpdateCheck!=null)
		mUpdateCheck.removeOnUpdateListener();
		super.onDestroy();

	}

	public void finish() {
		super.finish();
		overridePendingTransition(0, 0);
	}

	@Override
	public void onUpdateSuccess(Version version) {
		if(version.getforce_update()==1){//强制更新
			onShowForceUpdate(version);
		}
		else{
			onShowNoForceUpdate(version);
		}
	}

	@Override
	public void onUpdateFailed(int status,String msg) {
		getOnSvconfig();
	}
	public void onShowForceUpdate(final Version version){
		String updatecontent="";
		try{updatecontent=version.getDescription().replace("<br>", "\n");}catch(Exception e){}
		if(updatecontent!=null&&updatecontent.contains("\n")){
			dialog.setContent2Gravity(Gravity.LEFT);
		}
		dialog.setTitle(this.getResources().getString(R.string.mydailog_update_content_Force));
		dialog.setContent2(updatecontent);
		dialog.setSingle(this.getResources().getString(R.string.mydailog_confirm_update));
		dialog.show();
		dialog.setOnClickSingleListener(new onClickSingleListener() {
			@Override
			public void onClickSingle() {
				dialog.dismiss();
				onUpdate(true,version);
			}
		});
	}
    /**
     * 弹出不强制更新
     */
    public void onShowNoForceUpdate(final Version version){
    	String updatecontent="";
		try{updatecontent=version.getDescription().replace("<br>", "\n");}catch(Exception e){}
		if(updatecontent!=null&&updatecontent.contains("\n")){
			dialog.setContent2Gravity(Gravity.LEFT);
		}
    	dialog.setTitle(this.getResources().getString(R.string.mydailog_update_content));
    	dialog.setContent2(updatecontent);
    	dialog.setLeftButtonText(this.getResources().getString(R.string.mydailog_cancel_update));
		dialog.setRightButtonText(this.getResources().getString(R.string.mydailog_confirm_update));
		if (dialog != null && !dialog.isShowing()) {
			dialog.show();
		}
		dialog.setOnClickLeftListener(new onClickLeftListener() {	
			@Override
			public void onClickLeft() {
				dialog.dismiss();
				getOnSvconfig();
			}
		});
		dialog.setOnClickRightListener(new onClickRightListener() {
			
			@Override
			public void onClickRight() {
				dialog.dismiss();
				onUpdate(false,version);
			}
		});
    }
    /** 
     * 更新
     * @param isForce 是否强制更新
     */
    public void onUpdate(boolean isForce,Version version){
    	MyUpdateLoad mMyUpdateLoad=new MyUpdateLoad();
		mMyUpdateLoad.downloadApk(context, isForce,UpdateType.TYPE_QIDONG,version.getURL(),version.getVersion());
		ToastUtil.showToast(this,R.string.downloading);
		if (isForce) {
			context.stopService(new Intent(context, LoginService.class));
		} else {
			getOnSvconfig();

		}
    }
	@Override
	public void onBaiduUpdate() {
		getOnSvconfig();
	}
	@Override
	public void onQihooUpdate() {
		getOnSvconfig();
	}
	@Override
	public void onLocationResult(BDLocation location) {
		if(isLocation){
			isLocation=false;
			 if(!isStart){
		    		SPLASH_DELAY_MILLIS+=2000;
		    		onStartFragemnt(new WelcomeFragment(),0,0);
		     }
//			RequestUtils.requestLocationInfo(context,
//					location.getLongitude(), location.getLatitude(),
//					location.getProvince(), location.getCity());
		}
		
	}
	@Override
	public void onLocationResult(ReverseGeoCodeResult result) {
		if(isLocation){
		isLocation=false;
		 if(!isStart){
	    		SPLASH_DELAY_MILLIS+=2000;
	    		onStartFragemnt(new WelcomeFragment(),0,0);
	     }
//		RequestUtils.requestLocationInfo(context,
//				result.getLocation().longitude,
//				result.getLocation().latitude,
//				result.getAddressDetail().province,
//				result.getAddressDetail().city);
		}
		
	}
	@Override
	public void onLocationFail(boolean isnet) {
		// TODO Auto-generated method stub
		
	}

	 private void onStartFragemnt(Fragment baseFragment,int x,int y){
	        Bundle args = baseFragment.getArguments();
	        if(args==null){
	            args=new Bundle();
	        }
	        args.putInt(BasefragmentMsg.X, x);
	        args.putInt(BasefragmentMsg.Y, y);
	        baseFragment.setArguments(args);
	        getSupportFragmentManager().beginTransaction()
	                .addToBackStack("tag")
	                .add(android.R.id.content,baseFragment)
	                .commit();
	    }
	 @Override
	public void onBackPressed() {
	}
	@Override
	public void onNotifyData(DATA_STATUS data_status, DATA_TYPE data_type, int status, Object object) {
		switch (data_type) {
//	        case LOCATIONINFO:
//	        if (IsDataFail.isDataFail(status)) {
//	             return;
//	        }
//	        if(!isStart){
//	    		SPLASH_DELAY_MILLIS+=3000;
//	    		onStartFragemnt(new WelcomeFragment(),0,0);
//	    	}
//	        break;
			case SVCONFIG:
				if (IsDataFail.isDataFail(data_status)) {
					LogUtils.e("xxx", "---获取失败");
					startActivity(2);
				}else{
					if(object!=null){
						Svconfigs mSvconfigs=(Svconfigs)object;
						SDK.GetSDK().mClient.setTime(mSvconfigs.getTime_stamp());
					}
					startActivity(2);
				}
				break;
		 }
		
	}
	@Override
	public void onNotify(int type, JSONObject jb, Data msgs_data) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onNotify(int type, Object object) {
		// TODO Auto-generated method stub
		
	}

}
